

public class 最长公共前缀 {
    public static void main(String[] args) {
        String[] strs = {"dog","racecar","car"};
        String s = longestCommonPrefix(strs);
        System.out.println(s);
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        //让字符串组中的第一个作为最长公共前缀，与之后的每一个字符串进行比较
        String ans = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int j = 0;
            for (; j < ans.length() && j < strs[i].length(); j++) {
                if (ans.charAt(j) != strs[i].charAt(j)) {
                    break;
                }
            }
                //subString用于截取字符串
            ans = ans.substring(0, j);
            if (ans.equals(""))
              return "不存在公共前缀";
            }
            return ans;
        }
    }

